package com.example.application;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.application.model.UserMessage;

import java.util.ArrayList;
import java.util.List;

public class RecyclerViewDemoActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private UserMessageAdapter mUserMessageAdapter;
    private EditText mEditMsg;
    private List<UserMessage> mUserMessageList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view_demo);

        mEditMsg = findViewById(R.id.edit_user_msg);
        mUserMessageList = new ArrayList<>();

        mRecyclerView = findViewById(R.id.recv);
        mUserMessageAdapter = new UserMessageAdapter(mUserMessageList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mUserMessageAdapter);
    }

    public void onButtonSend(View view) {
        String content = mEditMsg.getText().toString();
        content = content.trim();
        if (content.length() == 0) {
            Toast.makeText(this, "不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        addSendMessage(content);
        addReceiveMessage("我接受到" + content);
    }

    private void addReceiveMessage(String content) {
        UserMessage userMsg = new UserMessage(content, UserMessage.TYPE_RECEIVE);
        mUserMessageList.add(userMsg);
        mUserMessageAdapter.notifyItemInserted(mUserMessageList.size() - 1);
        mRecyclerView.scrollToPosition(mUserMessageList.size() - 1);
        mEditMsg.setText("");
    }

    private void addSendMessage(String content) {
        UserMessage userMsg = new UserMessage(content, UserMessage.TYPE_SEND);
        mUserMessageList.add(userMsg);
        mUserMessageAdapter.notifyItemInserted(mUserMessageList.size() - 1);
        mRecyclerView.scrollToPosition(mUserMessageList.size() - 1);
        mEditMsg.setText("");
    }
}
